package com.sp.system.user.core.web.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Slf4j
@Service
public class LogInterceptor extends HandlerInterceptorAdapter {
    private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("Request StartTime");
    /*
    *
    * 开始拦截
    *
    * */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        startTimeThreadLocal.set(startTime);
        log.info("START The Method==>{}, startTime==>{}ms",request.getRequestURI(),new Date(startTime));
        return true;
    }
    /*
     * 结束拦截
     *
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

        long endTime = System.currentTimeMillis();
        long startTime = startTimeThreadLocal.get();
        log.info("END The Method==>{}, execute Time==>{}ms  ,endTime==>{} ",request.getRequestURI(),endTime- startTime,new Date(endTime));
        startTimeThreadLocal.remove();
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        if (modelAndView != null){
            log.info("ViewName: " + modelAndView.getViewName());
        }
    }


    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    }

}
